package com.arpa.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import com.arpa.core.utils.collection.CollectionUtil;
import com.arpa.oms.cache.UnpackRuleCache;
import com.arpa.oms.domain.entity.*;
import com.arpa.oms.domain.enums.OmsGoodTypeEnum;
import com.arpa.oms.domain.enums.OmsSaleUnpackStatusEnum;
import com.arpa.oms.domain.enums.OmsUnpackRuleEnum;
import com.arpa.oms.domain.enums.OmsUnpackRuleTypeEnum;
import com.arpa.oms.service.*;
import com.arpa.wms.cache.GoodsUnitConversionCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderDealServiceImpl implements IOrderDealService {
    @Autowired
    private UnpackRuleCache unpackRuleCache;
    @Autowired
    private IOmsGoodsRelationItemService iOmsGoodsRelationItemService;
    @Autowired
    private ISaleItemService iSaleItemService;
    @Autowired
    @Lazy
    private ISaleService iSaleService;
    @Autowired
    private ISalePacksService iSalePacksService;
    @Autowired
    private GoodsUnitConversionCache goodsUnitConversionCache;

    @Override
    public Sale composeToDetail(Sale sale) {
        //所有商品
        List<SaleItem> saleItems = sale.getSaleItemList();
        //销售商品中是组合类型的
        List<SaleItem> composeList = saleItems.stream().filter(v -> OmsGoodTypeEnum.GOOD_TYPE_COMPOSE.getCode().equals(v.getRecordType())).collect(Collectors.toList());
        //删除组合商品
        saleItems.removeAll(composeList);
        //处理组合商品
        for (SaleItem saleItem : composeList) {
            List<OmsGoodsRelationItem> goodsList = iOmsGoodsRelationItemService.list(new QueryWrapper<OmsGoodsRelationItem>().lambda().eq(OmsGoodsRelationItem::getGoodsRelationCode, saleItem.getGoodsCode()));
            for (OmsGoodsRelationItem item : goodsList) {
                SaleItem newSaleItem = new SaleItem();
                BeanUtil.copyProperties(item, newSaleItem);
                newSaleItem.setSaleCode(saleItem.getSaleCode());
                newSaleItem.setSaleUnit(item.getBasicUnit());
                newSaleItem.setSaleUnitName(item.getBasicUnitName());
                BigDecimal itemPlanBasicQuantity = saleItem.getPlanBasicQuantity().multiply(item.getPlanBasicQuantity());
                newSaleItem.setPlanBasicQuantity(itemPlanBasicQuantity);
                BigDecimal itemPlanQuantity = saleItem.getPlanQuantity().multiply(item.getPlanQuantity());
                newSaleItem.setPlanQuantity(itemPlanQuantity);
                newSaleItem.setUnitPrice(item.getDeliveryPrice());
                newSaleItem.setTaxUnitPrice(item.getDeliveryPrice());
                newSaleItem.setRemarks(saleItem.getRemarks());
                saleItems.add(newSaleItem);
            }
        }
        sale.setSaleItemList(saleItems);
        // 重新计算数量
        BigDecimal planQuantity = BigDecimal.ZERO;
        BigDecimal planBasicQuantity = BigDecimal.ZERO;
        for (SaleItem saleItem : sale.getSaleItemList()) {
            planBasicQuantity = planBasicQuantity.add(saleItem.getPlanBasicQuantity());
            planQuantity = planQuantity.add(saleItem.getPlanQuantity());
        }
        sale.setPlanQuantity(planQuantity);
        sale.setPlanBasicQuantity(planBasicQuantity);
        return sale;
    }

    @Override
    public List<SalePacks> unpack(Sale sale) {
        List<SalePacks> resultList = new ArrayList<>();
        Map<String, List<OmsUnpackRule>> shopRule = unpackRuleCache.getAllByShipmentCode(sale.getShipmentCode());
        SalePacks salePacks = new SalePacks();
        BeanUtil.copyProperties(sale, salePacks);
        //货主未配置拆单规则
        if (shopRule == null) {
            resultList.add(salePacks);
            return resultList;
        }

        List<OmsUnpackRule> ruleList = shopRule.get(sale.getShopCode());
        //店铺为配置规则
        if (CollectionUtil.isEmpty(ruleList)) {
            resultList.add(salePacks);
            return resultList;
        }
        //按商品
        List<OmsUnpackRule> goodRuleList = ruleList.stream().filter(v -> OmsUnpackRuleTypeEnum.BY_GOODS.getValue().equals(v.getRuleType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(goodRuleList)) {
            List<SalePacks> goodSaleList = new ArrayList<>();
            OmsUnpackRule goodRule = goodRuleList.get(0);
            List<SaleItem> saleItemList = sale.getSaleItemList();
            if (OmsUnpackRuleEnum.ALL_GOODS.getValue().equals(goodRule.getAllGoods())) {
                for (SaleItem saleItem : saleItemList) {
                    try {
                        goodSaleList.add(createSale(salePacks, Arrays.asList(saleItem)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                List<String> goodList = goodRule.getUnpackGoods();
                List<SaleItem> unpackList = new ArrayList<>();
                for (SaleItem saleItem : saleItemList) {
                    if (goodList.contains(saleItem.getGoodsCode())) {
                        goodSaleList.add(createSale(salePacks, Arrays.asList(saleItem)));
                    } else {
                        unpackList.add(saleItem);
                    }
                }
                if (CollectionUtil.isNotEmpty(unpackList)) {
                    goodSaleList.add(createSale(salePacks, unpackList));
                }
            }
            resultList = goodSaleList;
        } else {
            resultList.add(salePacks);
        }
        List<SalePacks> newResultList = new ArrayList<>();

        //按数量
        List<OmsUnpackRule> quantityRuleList = ruleList.stream().filter(v -> OmsUnpackRuleTypeEnum.BY_QUANTITY.getValue().equals(v.getRuleType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(quantityRuleList)) {
            OmsUnpackRule quantityRule = quantityRuleList.get(0);
            for (SalePacks s : resultList) {
                newResultList.addAll(unpackByCount(s, quantityRule));
            }
            resultList = newResultList;
        }

        //按重量
        quantityRuleList = ruleList.stream().filter(v -> OmsUnpackRuleTypeEnum.BY_WEIGHT.getValue().equals(v.getRuleType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(quantityRuleList)) {
            OmsUnpackRule unpackRule = quantityRuleList.get(0);
            newResultList = new ArrayList<>();
            for (SalePacks s : resultList) {
                newResultList.addAll(unpackByWeight(s, unpackRule));
            }
            resultList = newResultList;
        }

        //按体积
        quantityRuleList = ruleList.stream().filter(v -> OmsUnpackRuleTypeEnum.BY_VOLUME.getValue().equals(v.getRuleType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(quantityRuleList)) {
            OmsUnpackRule volumeRule = quantityRuleList.get(0);
            newResultList = new ArrayList<>();
            for (SalePacks s : resultList) {
                newResultList.addAll(unpackByVolume(s, volumeRule));
            }
            resultList = newResultList;
        }

        //重新计算数量
//        int i=1;
//        for (Sale s : resultList) {
//            s.setCode(s.getCode() + "-" + i);
//            refrehSale(s);
//            i++;
//        }
        iSalePacksService.create(resultList);
        return resultList;
    }

    /**
     * 按体积拆单
     * @param salePacks
     * @param volumeRule
     * @return
     */
    private List<SalePacks> unpackByVolume(SalePacks salePacks, OmsUnpackRule volumeRule) {
        List<SalePacks> resultList = new ArrayList<>();
        BigDecimal volume = volumeRule.getRuleValue();
        List<SaleItem> saleItems = salePacks.getSaleItemList();
        saleItems.sort(new Comparator<SaleItem>() {
            @Override
            public int compare(SaleItem o1, SaleItem o2) {
                BigDecimal goodsVolume1 = goodsUnitConversionCache.getBasicUnitVolume(o1.getGoodsCode());
                BigDecimal goodsVolume2 = goodsUnitConversionCache.getBasicUnitVolume(o2.getGoodsCode());
                return goodsVolume2.compareTo(goodsVolume1);
            }
        });
        List<SaleItem> list = new ArrayList<>();
        Set<String> codes = new HashSet<>();
        for (SaleItem item : saleItems) {
            BigDecimal goodsVolume = goodsUnitConversionCache.getBasicUnitVolume(item.getGoodsCode());
            BigDecimal num = BigDecimal.ONE;
            BigDecimal totalVolume = BigDecimal.ZERO;
            for (int i=0; i<item.getPlanQuantity().intValue(); i++) {
                BigDecimal currentVolume = goodsVolume.multiply(num);
                totalVolume = totalVolume.add(currentVolume);
                if (codes.contains(item.getCode())) {
                    list.stream().filter(v -> v.getCode().equals(item.getCode())).collect(Collectors.toList()).forEach(e -> {
                        BigDecimal n = e.getPlanQuantity().add(BigDecimal.ONE);
                        e.setPlanQuantity(n);
                        e.setPlanBasicQuantity(n);
                    });
                } else {
                    codes.add(item.getCode());
                    SaleItem saleItem = new SaleItem();
                    BeanUtil.copyProperties(item, saleItem);
                    saleItem.setPlanBasicQuantity(num);
                    saleItem.setPlanQuantity(num);
                    list.add(saleItem);
                }
                if (totalVolume.compareTo(volume) == 1) {
                    resultList.add(createSale(salePacks, list));
                    list = new ArrayList<>();
                    codes.clear();
                    num = BigDecimal.ZERO;
                    totalVolume = BigDecimal.ZERO;
                }
                num = num.add(BigDecimal.ONE);
            }
        }
        if (list.size() > 0) {
            resultList.add(createSale(salePacks, list));
        }
        return resultList;
    }

    /**
     * 按重量拆单
     * @param salePacks
     * @param weightRule
     * @return
     */
    private List<SalePacks> unpackByWeight(SalePacks salePacks, OmsUnpackRule weightRule) {
        List<SalePacks> resultList = new ArrayList<>();
        BigDecimal weight = weightRule.getRuleValue();
        List<SaleItem> saleItems = salePacks.getSaleItemList();
        saleItems.sort(new Comparator<SaleItem>() {
            @Override
            public int compare(SaleItem o1, SaleItem o2) {
                BigDecimal goodsWeight1 = goodsUnitConversionCache.getBasicUnitWeight(o1.getGoodsCode());
                BigDecimal goodsWeight2 = goodsUnitConversionCache.getBasicUnitWeight(o2.getGoodsCode());
                return goodsWeight2.compareTo(goodsWeight1);
            }
        });
        List<SaleItem> list = new ArrayList<>();
        Set<String> codes = new HashSet<>();
        for (SaleItem item : saleItems) {
            BigDecimal goodsWeight = goodsUnitConversionCache.getBasicUnitWeight(item.getGoodsCode());
            BigDecimal num = BigDecimal.ONE;
            BigDecimal totalWeight = BigDecimal.ZERO;
            for (int i=0; i<item.getPlanQuantity().intValue(); i++) {
                BigDecimal currentWeight = goodsWeight.multiply(num);
                totalWeight = totalWeight.add(currentWeight);
                if (codes.contains(item.getCode())) {
                    list.stream().filter(v -> v.getCode().equals(item.getCode())).collect(Collectors.toList()).forEach(e -> {
                        BigDecimal n = e.getPlanQuantity().add(BigDecimal.ONE);
                        e.setPlanQuantity(n);
                        e.setPlanBasicQuantity(n);
                    });
                } else {
                    codes.add(item.getCode());
                    SaleItem saleItem = new SaleItem();
                    BeanUtil.copyProperties(item, saleItem);
                    saleItem.setPlanBasicQuantity(num);
                    saleItem.setPlanQuantity(num);
                    list.add(saleItem);
                }
                if (totalWeight.compareTo(weight) == 1) {
                    resultList.add(createSale(salePacks, list));
                    list = new ArrayList<>();
                    codes.clear();
                    num = BigDecimal.ZERO;
                    totalWeight = BigDecimal.ZERO;
                }
                num = num.add(BigDecimal.ONE);
            }
        }
        if (list.size() > 0) {
            resultList.add(createSale(salePacks, list));
        }
        return resultList;
    }
    /**
     * 按数量拆单
     * @param salePacks
     * @param quantityRule
     * @return
     */
    private List<SalePacks> unpackByCount(SalePacks salePacks, OmsUnpackRule quantityRule) {
        List<SalePacks> resultList = new ArrayList<>();
        BigDecimal count = quantityRule.getRuleValue();
        List<SaleItem> saleItems = salePacks.getSaleItemList();
        List<SaleItem> newSaleItems = new ArrayList<>();
        saleItems.sort(new Comparator<SaleItem>() {
            @Override
            public int compare(SaleItem o1, SaleItem o2) {
                return o2.getPlanQuantity().compareTo(o2.getPlanQuantity());
            }
        });
        if (OmsUnpackRuleEnum.ALL_GOODS.getValue().equals(quantityRule.getAllGoods())) {
            for (SaleItem si : saleItems) {
                BigDecimal itemCount = si.getPlanQuantity();
                if (itemCount.compareTo(count) > 0) {
                    //拆单
                    while (itemCount.compareTo(count) > 0) {
                        BigDecimal newCount = count.setScale(0, BigDecimal.ROUND_DOWN);
                        SaleItem newSaleItem = new SaleItem();
                        BeanUtil.copyProperties(si, newSaleItem);
                        newSaleItem.setPlanBasicQuantity(newCount);
                        newSaleItem.setPlanQuantity(newCount);
                        List<SaleItem> list = new ArrayList<>();
                        list.add(newSaleItem);
                        resultList.add(createSale(salePacks, list));
                        itemCount = itemCount.subtract(newCount);
                    }
                    if (itemCount.compareTo(BigDecimal.ZERO) > 0) {
                        SaleItem newSaleItem = new SaleItem();
                        BeanUtil.copyProperties(si, newSaleItem);
                        newSaleItem.setPlanBasicQuantity(itemCount);
                        newSaleItem.setPlanQuantity(itemCount);
                        List<SaleItem> list = new ArrayList<>();
                        list.add(newSaleItem);
                        resultList.add(createSale(salePacks, list));
                    }
                } else {
                    newSaleItems.add(si);
                }
            }
            if (IterUtil.isNotEmpty(newSaleItems)) {
                salePacks.setSaleItemList(newSaleItems);
                // 重新计算数量
                salePacks = createSale(salePacks, salePacks.getSaleItemList());
                resultList.add(salePacks);
            }
        } else {
            List<String> goods = quantityRule.getUnpackGoods();

            for (SaleItem si : saleItems) {
                BigDecimal itemCount = si.getPlanQuantity();
                if (goods.contains(si.getGoodsCode()) && itemCount.compareTo(count) > 0) {
                    //拆单
                    while (itemCount.compareTo(count) > 0) {
                        SaleItem newSaleItem = new SaleItem();
                        BeanUtil.copyProperties(si, newSaleItem);
                        newSaleItem.setPlanBasicQuantity(count);
                        newSaleItem.setPlanQuantity(count);
                        List<SaleItem> list = new ArrayList<>();
                        list.add(newSaleItem);
                        resultList.add(createSale(salePacks, list));
                        itemCount = itemCount.subtract(count);
                    }
                    if (itemCount.compareTo(BigDecimal.ZERO) > 0) {
                        SaleItem newSaleItem = new SaleItem();
                        BeanUtil.copyProperties(si, newSaleItem);
                        newSaleItem.setPlanBasicQuantity(itemCount);
                        newSaleItem.setPlanQuantity(itemCount);
                        List<SaleItem> list = new ArrayList<>();
                        list.add(newSaleItem);
                        resultList.add(createSale(salePacks, list));
                    }
                } else {
                    newSaleItems.add(si);
                }
            }
            if (IterUtil.isNotEmpty(newSaleItems)) {
                salePacks.setSaleItemList(newSaleItems);
                resultList.add(salePacks);
            }
        }
        return resultList;
    }

    private SalePacks createSale(SalePacks salePacks, List<SaleItem> saleItems) {
        SalePacks newSale = new SalePacks();
        BeanUtil.copyProperties(salePacks, newSale);
        BigDecimal planQuantity = BigDecimal.ZERO;
        BigDecimal planBasicQuantity = BigDecimal.ZERO;
        BigDecimal refundQuantity = BigDecimal.ZERO;
        BigDecimal refundBasicQuantity = BigDecimal.ZERO;
        BigDecimal totalMoney = BigDecimal.ZERO;
        for (SaleItem saleItem: saleItems) {
            planQuantity = planQuantity.add(saleItem.getPlanQuantity());
            planBasicQuantity = planBasicQuantity.add(saleItem.getPlanBasicQuantity());
            refundQuantity = refundQuantity.add(saleItem.getRefundQuantity());
            refundBasicQuantity = refundBasicQuantity.add(saleItem.getRefundBasicQuantity());
            totalMoney = totalMoney.add(saleItem.getTotalMoney());
        }
        newSale.setPlanQuantity(planQuantity);
        newSale.setPlanBasicQuantity(planBasicQuantity);
        newSale.setRefundQuantity(refundQuantity);
        newSale.setRefundBasicQuantity(refundBasicQuantity);
        newSale.setPaymentAmount(totalMoney);
        newSale.setOwedAmount(totalMoney);
        newSale.setPayAmount(totalMoney);
        newSale.setUnpackStatus(OmsSaleUnpackStatusEnum.PACK.getValue());
        newSale.setSaleItemList(saleItems);
        return newSale;
    }

    @Override
    public List<Sale> merge(List<Sale> list) {
        List<Sale> resultData = new ArrayList<>();
        resultData = list.stream().filter(v -> StringUtils.isBlank(v.getMergeCode())).collect(Collectors.toList());
        List<Sale> mergeList = list.stream().filter(v -> StringUtils.isNotBlank(v.getMergeCode())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(mergeList)) {
            return resultData;
        }
        //更新合单未选择审核销售单
        List<String> mergeCodeList = mergeList.stream().map(v -> v.getMergeCode()).collect(Collectors.toList());
        List<String> saleCodeList = mergeList.stream().map(v -> v.getCode()).collect(Collectors.toList());
        iSaleService.update(new UpdateWrapper<Sale>().lambda().in(Sale::getMergeCode, mergeCodeList).ne(Sale::getCode, saleCodeList).setSql(" merge_code = null "));

        for (Sale sale : mergeList) {
            List<SaleItem> saleItems = iSaleItemService.list(new QueryWrapper<SaleItem>().lambda().eq(SaleItem::getSaleCode, sale.getCode()));
            sale.setSaleItemList(saleItems);
        }
        Map<String, List<Sale>> map = mergeList.stream().collect(Collectors.groupingBy(Sale::getMergeCode));
        for (Map.Entry<String, List<Sale>> entry : map.entrySet()) {
            List<Sale> saleList = entry.getValue();
            if (saleList.size() > 1) {
                Sale sale = new Sale();
                BeanUtils.copyProperties(saleList.get(0), sale);
                List<SaleItem> saleItems = new ArrayList<>();
                BigDecimal payAmount = BigDecimal.ZERO;
                BigDecimal planQuantity = BigDecimal.ZERO;
                BigDecimal planBasicQuantity = BigDecimal.ZERO;
                BigDecimal actualQuantity = BigDecimal.ZERO;
                BigDecimal actualBasicQuantity = BigDecimal.ZERO;
                BigDecimal refundQuantity = BigDecimal.ZERO;
                BigDecimal refundBasicQuantity = BigDecimal.ZERO;
                BigDecimal paymentAmount = BigDecimal.ZERO;
                BigDecimal owedAmount = BigDecimal.ZERO;
                BigDecimal discountAmount = BigDecimal.ZERO;
                BigDecimal otherAmount = BigDecimal.ZERO;
                for (Sale s : saleList) {
                    payAmount = payAmount.add(s.getPayAmount());
                    planQuantity = planQuantity.add(s.getPlanQuantity());
                    planBasicQuantity = planBasicQuantity.add(s.getPlanBasicQuantity());
                    actualQuantity = actualQuantity.add(s.getActualQuantity());
                    actualBasicQuantity = actualBasicQuantity.add(s.getActualBasicQuantity());
                    refundQuantity = refundQuantity.add(s.getRefundQuantity());
                    refundBasicQuantity = refundBasicQuantity.add(s.getRefundBasicQuantity());
                    paymentAmount = paymentAmount.add(s.getPaymentAmount());
                    owedAmount = owedAmount.add(s.getOwedAmount());
//                    discountAmount = discountAmount.add(s.getDiscountAmount());
                    otherAmount = otherAmount.add(s.getOtherAmount());
                    saleItems.addAll(s.getSaleItemList());
                }
                sale.setCode(sale.getMergeCode());
                sale.setPayAmount(payAmount);
                sale.setPlanQuantity(planQuantity);
                sale.setPlanBasicQuantity(planBasicQuantity);
                sale.setActualQuantity(actualQuantity);
                sale.setActualBasicQuantity(actualBasicQuantity);
                sale.setRefundQuantity(refundQuantity);
                sale.setRefundBasicQuantity(refundBasicQuantity);
                sale.setPaymentAmount(paymentAmount);
//                sale.setDiscountAmount(discountAmount);
                sale.setOtherAmount(otherAmount);
                sale.setSaleItemList(mergeGoods(saleItems, sale.getCode()));
                resultData.add(sale);
            } else {
                saleList.get(0).setMergeCode(null);
                resultData.add(saleList.get(0));
            }
        }

        return resultData;
    }

    private List<SaleItem> mergeGoods(List<SaleItem> saleItems, String saleCode) {
        Map<String, List<SaleItem>> map = saleItems.stream().collect(Collectors.groupingBy(v -> v.getGoodsCode()));
        List<SaleItem> resultData = new ArrayList<>();
        for (Map.Entry<String, List<SaleItem>> m : map.entrySet()) {
            List<SaleItem> itemList = m.getValue();
            if (itemList.size() > 1) {
                //  合并商品
                SaleItem saleItem = new SaleItem();
                BeanUtils.copyProperties(itemList.get(0), saleItem);
                saleItem.setCode(IdUtil.simpleUUID());
                saleItem.setSaleCode(saleCode);
                BigDecimal planQuantity = BigDecimal.ZERO;
                BigDecimal planBasicQuantity = BigDecimal.ZERO;
                BigDecimal actualQuantity = BigDecimal.ZERO;
                BigDecimal actualBasicQuantity = BigDecimal.ZERO;
                BigDecimal amountMoney = BigDecimal.ZERO;
                BigDecimal taxMonye = BigDecimal.ZERO;
                BigDecimal totalMoney = BigDecimal.ZERO;
                BigDecimal refundQuantity = BigDecimal.ZERO;
                BigDecimal refundBasicQuantity = BigDecimal.ZERO;
                for (SaleItem item : itemList) {
                    planQuantity = planQuantity.add(item.getPlanQuantity());
                    planBasicQuantity = planBasicQuantity.add(item.getPlanBasicQuantity());
                    actualQuantity = actualQuantity.add(item.getActualQuantity());
                    actualBasicQuantity = actualBasicQuantity.add(item.getActualBasicQuantity());
                    amountMoney = amountMoney.add(item.getAmountMoney());
                    taxMonye = taxMonye.add(item.getTaxMoney());
                    totalMoney = totalMoney.add(item.getTotalMoney());
                    refundQuantity = refundQuantity.add(item.getRefundQuantity());
                    refundBasicQuantity = refundBasicQuantity.add(item.getRefundBasicQuantity());
                }
                saleItem.setPlanQuantity(planQuantity);
                saleItem.setPlanBasicQuantity(planBasicQuantity);
                saleItem.setActualQuantity(actualQuantity);
                saleItem.setActualBasicQuantity(actualBasicQuantity);
                saleItem.setAmountMoney(amountMoney);
                saleItem.setTaxMoney(taxMonye);
                saleItem.setTotalMoney(totalMoney);
                saleItem.setRefundQuantity(refundQuantity);
                saleItem.setRefundBasicQuantity(refundBasicQuantity);
                if (OmsGoodTypeEnum.GOOD_TYPE_COMPOSE.getCode().equals(saleItem.getRecordType())) {
                    List<SaleItem> list = composeToList(saleItem);
                    if (CollectionUtil.isNotEmpty(list)) {
                        resultData.addAll(list);
                    }
                } else {
                    resultData.add(saleItem);
                }
            } else {
                SaleItem saleItem = itemList.get(0);
                saleItem.setSaleCode(saleCode);
                resultData.add(itemList.get(0));
            }
        }
        return resultData;
    }

    private List<SaleItem> composeToList(SaleItem saleItem) {
        List<SaleItem> saleItems = new ArrayList<>();
        List<OmsGoodsRelationItem> list = iOmsGoodsRelationItemService.list(new QueryWrapper<OmsGoodsRelationItem>().lambda().eq(OmsGoodsRelationItem::getGoodsRelationCode, saleItem.getGoodsCode()));
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        BigDecimal deliveryMoney = saleItem.getAmountMoney().divide(BigDecimal.valueOf(list.size()), 6, BigDecimal.ROUND_HALF_UP);
        for (OmsGoodsRelationItem item : list) {
            SaleItem si = new SaleItem();
            si.setCode(IdUtil.simpleUUID());
            si.setSaleCode(saleItem.getSaleCode());
            BeanUtils.copyProperties(item, si);
            si.setPlanQuantity(saleItem.getPlanBasicQuantity());
            si.setPlanBasicQuantity(saleItem.getPlanBasicQuantity());
            si.setSaleUnit(si.getBasicUnit());
            si.setSaleUnitName(si.getBasicUnitName());
            si.setActualBasicQuantity(saleItem.getPlanBasicQuantity());
            si.setActualQuantity(saleItem.getPlanBasicQuantity());
            si.setAmountMoney(deliveryMoney);
            si.setTotalMoney(deliveryMoney);
            si.setRecordType(OmsGoodTypeEnum.GOOD_TYPE_COMPOSE.getCode());
            saleItems.add(si);
        }
        return saleItems;
    }

}
